require 'json'
require 'oembed'

module Textp

  class HtmlHelper
    def initialize(text)
      @text     = text
      @parser   = Parser.new(text)
    end

    def links
      links = { :links => @parser.links }
    end

    def links_content
      oembed_data = {}
      OEmbed::Providers.register(OEmbed::Providers::Youtube)
      @parser.links.each do |link|
        resource = OEmbed::Providers.get(link)
        oembed_data[link] ||= {}
        oembed_data[link][:html] ||= resource.html
        oembed_data[link][:provider] ||= {
          :endpoint => resource.provider.endpoint
        }
      end
      oembed_data
    end

    def parser
      @parser
    end

    def response
      json_string = {
        :links => @parser.links,
        :oembed_data => links_content
      }.to_json
    end

    def replacement_content
      content = @text
      @parser.links.each do |link|
        html_content = links_content[link][:html]
        content.gsub!(link, html_content)
      end
      content
    end
  end

end